//用户相关的小仓库
import { defineStore } from "pinia";
//引入API接口
import { reqLogin, reqUserInfo, reqLayout } from "@/api/user";
//引入API接口的数据类型
import type { loginData } from "@/api/user/type";
//引入仓库数据类型
import type { UserState } from "./type/type";
//引入本地存储数据的工具方法
import { SET_TOKEN, GET_TOKEN, REMOVE_TOKEN } from "@/utils/token";
//引入常量路由
import { constantRoutes, asyncRoutes, anyRoutes } from "@/router/routes";
import router from "@/router";

//过滤路由
const filterAsyncRoute = (asyncRoutes: any, routes: any) => {
  return asyncRoutes.filter((item: any) => {
    if (routes.includes(item.name)) {
      if (item.children && item.children.length > 0) {
        item.children = filterAsyncRoute(item.children, routes);
      }
      return true;
    }
  });
};
//创建并暴露用户小仓库
const useUserStore = defineStore("User", {
  //存储数据
  state: (): UserState => {
    return {
      token: GET_TOKEN(),
      menuRoutes: constantRoutes, //菜单路由
      username: "",
      avatar: "",
    };
  },
  //   异步｜逻辑
  actions: {
    //用户登录
    async userLogin(data: loginData) {
      let result = await reqLogin(data);
      // console.log(result);
      if (result.code == 200) {
        this.token = result.data;
        SET_TOKEN(result.data);
        return "ok";
      } else {
        return Promise.reject(new Error(result.message));
      }
    },
    //用户信息
    async userInfo() {
      let result = await reqUserInfo();
      // console.log(result);
      if (result.code == 200) {
        this.username = result.data.name;
        this.avatar = result.data.avatar;
        //计算当前用户所需要的异步路由
        let userAsyncRoute = filterAsyncRoute(asyncRoutes, result.data.routes);
        // console.log(userAsyncRoute);
        //菜单所需要的数据整理
        this.menuRoutes = [...constantRoutes, ...userAsyncRoute, anyRoutes];
        //目前路由器管理的只有常量路由:用户计算完毕异步路由任意路由动态追加
        [...userAsyncRoute, anyRoutes].forEach((route: any) => {
          router.addRoute(route);
        });
        // console.log(router.getRoutes());//获取到当前所有的路由

        return "ok";
      } else {
        return Promise.reject(new Error(result.message));
      }
    },
    //退出登录
    async userLayout() {
      let result = await reqLayout();
      if (result.code == 200) {
        this.avatar = "";
        this.username = "";
        this.token = "";
        REMOVE_TOKEN();
        return "ok";
      } else {
        return Promise.reject(new Error(result.message));
      }
    },
  },
  getters: {},
});
export default useUserStore;
